package pl.elka.simulator.core.configurationCommand.impl;

import java.util.List;

import pl.elka.simulator.core.Position;
import pl.elka.simulator.core.Treasure;
import pl.elka.simulator.core.configurationCommand.ConfigurationCommandType;
import pl.elka.simulator.core.configurationCommand.ICommandParam;
import pl.elka.simulator.core.configurationCommand.IConfigurationCommand;
import pl.elka.simulator.core.configurationCommand.ables.IAbleToConfiguration;
import pl.elka.simulator.core.configurationCommand.ables.IAbleToTreasureConfiguration;

public class DeleteTreasureConfigurationCommand implements IConfigurationCommand{

	private ICommandParam param;
		
	@Override
	public IConfigurationCommand newInstance() {		
		return new DeleteTreasureConfigurationCommand();
	}

	@Override
	public void setParam(ICommandParam param) {
		this.param = param;
		
	}

	@Override
	public ICommandParam getParam() {		
		return param;
	}

	@Override
	public ConfigurationCommandType getType() {
		return ConfigurationCommandType.DeleteTreasureConfigurationCommand;
	}

	@Override
	public void execute(IAbleToConfiguration able) {
		IAbleToTreasureConfiguration ta = (IAbleToTreasureConfiguration) able;
		
		List<Treasure> treasures = ta.getTreasures();
		
		Position position = CommandUtils.getPosition(this);
		Treasure toDelete = findTreasureByPosition(treasures,position);
		if(toDelete!=null){
			treasures.remove(toDelete);
			return;
		}
		
		ta.setTreasures(treasures);
	}
	
	private Treasure findTreasureByPosition(List<Treasure> treasures, Position position) {		
		float px = position.getX();
		float py = position.getY();
		for(Treasure n:treasures){
			float r = n.getRadius();
			float nx = n.getPosition().getX();
			float ny = n.getPosition().getY();
			
			if(nx-r<px && nx+r>px && ny+r>py && ny-r<py){
				//TODO mozna doimplementowac dokladniejszy warunek
				return n;
			}
		}
		return null;
	}

}
